package com.wms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wms.bean.PageBean;
import com.wms.entity.StockTakingTask;
import com.wms.mapper.ReviewAdjustmentsDetailGroupMapper;
import com.wms.mapper.StockTakingTaskMapper;
import com.wms.service.StockTakingTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class StockTakingTaskServiceImpl implements StockTakingTaskService {
    @Autowired
    StockTakingTaskMapper stockTakingTaskMapper;

    @Autowired
    ReviewAdjustmentsDetailGroupMapper reviewAdjustmentsDetailGroupMapper;

    /**
     * 分页查询未完成的任务列表
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageBean queryAllNoFinish(int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        List list =stockTakingTaskMapper.queryAllNoFinish();
        PageInfo pageInfo = new PageInfo(list);
        return new PageBean(page,pageSize,pageInfo.getTotal(),list);
    }

    /**
     * 分页查询已完成的任务列表
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageBean queryAllFinish(int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        List list =stockTakingTaskMapper.queryAllFinish();
        PageInfo pageInfo = new PageInfo(list);
        return new PageBean(page,pageSize,pageInfo.getTotal(),list);

    }

    @Override
    public int deleteTaskByTaskCode(String code) {
        try{
            int status = stockTakingTaskMapper.queryTaskStatusByCode(code);
            if(status!=1){
                throw new RuntimeException("只有待盘点状态的任务才能删除，当前状态：" + status);
            }
            int rs = stockTakingTaskMapper.deleteTaskByTaskCode(code);
            if(rs > 0) {
            return rs;
            } else {
                throw new RuntimeException("数据库删除操作失败");
            }
        }catch (Exception e){
            // 记录原始异常信息，便于调试
            e.printStackTrace();
            throw new RuntimeException("删除失败: " + e.getMessage());
        }
    }

    @Override
    public int updateTaskIscancelByCode(String code) {
        try{
            int status = stockTakingTaskMapper.queryTaskStatusByCode(code);
            if (status == 1 || status == 2 || status == 3){
                int rs = stockTakingTaskMapper.updateTaskIscancelByCode(code);
                if (rs > 0) {
                    stockTakingTaskMapper.updateTaskSeqByCode(code);
                    return rs;
                } else {
                    throw new RuntimeException("作废操作失败");
                }
            } else {
                throw new RuntimeException("当前任务状态不允许作废");
            }
        } catch (Exception e){
            throw new RuntimeException("作废失败: " + e.getMessage());
        }
    }
}
